package com.archstudy.springcloud.netty.util;

import com.alibaba.fastjson.JSONObject;
import groovy.util.logging.Slf4j;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class HttpUtil {


    public static void closeUnauthChannelAfterWrite(ChannelHandlerContext ctx, String content) {
        FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.UNAUTHORIZED,
//                        HttpResponseStatus.OK,
                Unpooled.copiedBuffer(JSONObject.toJSONString(content), CharsetUtil.UTF_8));

        resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=utf8");

        // 2.发送
        // 注意必须在使用完之后，close channel
        ChannelFuture sendFuture = ctx.writeAndFlush(resp);
        sendFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                future.channel().close();


            }
        });
    }

}
